<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var hasPathSum = function (root, targetSum) {
                if (!root) return false
                //注意，有个细节，sum必须要有默认值，即root根节点。因为它每次遍历都是从左右子节点开始的
                return preOrder(root, root.val)
                function preOrder(cur, sum) {
                    if (!cur.left && !cur.right && sum == targetSum) {
                        return true
                    }
                    if (!cur.left && !cur.right) {
                        return false
                    }
                    if (cur.left) {
                        sum += cur.left.val
                        //如果有满足条件的边，就可以直接return true了，直接一路返回结果
                        if (preOrder(cur.left, sum)) return true
                        //如果没有满足条件的边，进行回溯，即sum变回原值，继续判断cur.right
                        sum -= cur.left.val
                    }
                    if (cur.right) {
                        sum += cur.right.val
                        if (preOrder(cur.right, sum)) return true
                        sum -= cur.right.val
                    }
                    //如果遍历完了所有边，找不到。最后，return false。不然是undefined。
                    return false
                }
            }
        </script>
    </body>
</html>
